package com.chinaunicom.emergency.action;

import com.alibaba.fastjson.JSONObject;
import com.chinaunicom.emergency.exception.OAuthException;
import com.chinaunicom.emergency.model.YjglOrg;
import com.chinaunicom.emergency.model.YjglUser;
import com.chinaunicom.emergency.util.HttpUtil;
import com.chinaunicom.emergency.exception.BusiException;
import com.chinaunicom.emergency.exception.CheckException;
import com.chinaunicom.emergency.repository.OrgRepository;
import com.chinaunicom.emergency.repository.UsersRepository;
import com.chinaunicom.emergency.service.BaseService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @author liliang
 * @date 2019-12-13
 */
@Log4j2
@ControllerAdvice
@ResponseBody
public abstract class BaseAction {

    @Autowired
    protected HttpServletRequest request;
    @Autowired
    private UsersRepository usersRepository;
    @Autowired
    private OrgRepository orgRepository;
    @Autowired
    protected BaseService baseService;

    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Object paramMissErrorHandler(MissingServletRequestParameterException e) {
        return error("参数" + e.getParameterName() + "不能为空");
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Object paramMethodNotSupportedHandler(HttpRequestMethodNotSupportedException e) {
        return error("请求的method不被支持 ："+e.getMethod());
    }

    @ExceptionHandler(Exception.class)
    public Object handleException(HttpServletResponse response, Exception e) {
        response.setStatus(400);
        if (e instanceof CheckException) {
            return error(e.getMessage());
        } else if (e instanceof BusiException) {
            return error(e.getMessage());
        }else if (e instanceof OAuthException) {
            return error(e.getMessage());
        }else {
            log.error("action处理错误", e);
            return error("系统出错啦，请联系管理员");
        }
    }

    public String getIp(){
        return HttpUtil.getRealIP(request);
    }

    public Pageable getPageable(Map map) {
        return getPageable(map, null);
    }

    public Pageable getPageable(Map map, Sort sort) {
        Integer size = Integer.parseInt(map.get("limit").toString());
        Integer page = (Integer.parseInt(map.get("page").toString()) - 1);
        Pageable pageable = null;
        if (sort == null) {
            pageable = PageRequest.of(page, size);
        } else {
            pageable = PageRequest.of(page, size, sort);
        }
        return pageable;
    }

    public Pageable getPageable(Integer limit,Integer page, Sort sort) {
        Pageable pageable = null;
        if (sort == null) {
            pageable = PageRequest.of(page -1 , limit);
        } else {
            pageable = PageRequest.of(page -1 , limit, sort);
        }
        return pageable;
    }

    public Integer getPage(Integer page,Integer limit){
        return (page - 1) * limit;
    }

    public JSONObject success(Object obj) {
        JSONObject json = new JSONObject();
        json.put("resultCode", 200);
        json.put("resultMessage", "success");
        json.put("data", obj);
        return json;
    }
    public Object success(Object obj,Integer resultCode) {
        JSONObject json = new JSONObject();
        json.put("resultCode", resultCode);
        json.put("data", obj);
        return json;
    }

    public Object success(Object obj,String message) {
        JSONObject json = new JSONObject();
        json.put("resultCode", 200);
        json.put("resultMessage", message);
        json.put("data", obj);
        return json;
    }

    public Object success(Object obj,Integer resultCode,String message) {
        JSONObject json = new JSONObject();
        json.put("resultCode", resultCode);
        json.put("resultMessage", message);
        json.put("data", obj);
        return json;
    }

    public Object success() {
        JSONObject json = new JSONObject();
        json.put("resultCode", 200);
        json.put("resultMessage", "success");
        return json;
    }

    public Object page(Page page) {
        JSONObject json = new JSONObject();
        json.put("code", 0);
        json.put("count", page.getTotalElements());
        json.put("data", page.getContent());
        json.put("resultCode", 200);
        json.put("resultMessage", "success");
        return json;
    }

    public static Object error(String errorMsg) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("resultCode", 400);
        jsonObject.put("resultMsg", errorMsg);
        return new ResponseEntity<Map<String, Object>>(jsonObject, HttpStatus.BAD_REQUEST);
    }

    public String getCurrUserId() throws CheckException {
        String userName = (String) request.getAttribute("userName");
        log.info("获取当前用户：" + userName);
        if(StringUtils.isBlank(userName)){
            userName = "";
        }
        return userName.toUpperCase();
    }

    public Object error(Integer resultCode,String message) {
        JSONObject json = new JSONObject();
        json.put("resultCode", resultCode);
        json.put("resultMessage", message);
        return json;
    }


    //根据用户名查询用户信息
    public YjglUser getUserInfoByUserNo(String userNo){
        YjglUser cpcUser = usersRepository.findYjglUserByUserNameAndIsSoftDel(userNo,0);
        if(null != cpcUser){
            cpcUser.setPassword(null);
            cpcUser.setOldPassword(null);
        }
        return cpcUser;
    }

    //获取用户姓名
    public String getUserName(String userNo){
        YjglUser user = getUserInfoByUserNo(userNo);
        if(null == user){
            return "1";
        }
        return user.getRealName();
    }

    public YjglOrg getOrgByOrgId(String orgId){
        return orgRepository.findByOrgIdAndIsSoftDel(orgId,0);
    }

    //递归调用查询所有子机构,
    public List<String> getChild(List orgList,List<String> orgs){
        for(String orgId : orgs){
            List<String> childs = orgRepository.findOrgIdByParentId(orgId);
            if(childs!= null && childs.size() > 0){
                orgList.addAll(childs);
                getChild(orgList,childs);
            }
        }
        return orgList;
    }

    //递归调用查询所有父机构,
    public List<String> getFathers(List orgList, String subId) {
        YjglOrg org = orgRepository.findByOrgIdAndIsSoftDel(subId, 0);
        if (org != null) {
            orgList.add(org.getParentId());
            getFathers(orgList, org.getParentId());
        }
        return orgList;
    }
}
